<?php
class Sale{

	protected $items;
	protected $coupons;

	public function getInputCodes()
	{
		$arrCodes   = array(-1);
        if( isset($_COOKIE['sale_item_code']) )
        {
            $arrCodes = json_decode($_COOKIE['sale_item_code'], true);
        }
        return $arrCodes;
	}

	public function getAllCodesWithBind()
	{
		$arrCodes	= $this->getInputCodes();
        $arrBind    = array();
        foreach($arrCodes as $key => $value)
        {
            //Should ensure all input is expected and valid
            $arrBind[':code'.$key] = (int)$value;
        }
        return $arrBind;
	}
	public function getAllItems()
	{
		if( $this->items !== NULL)
		{
			return $this->items;
		}
		$criteria   = new CDbCriteria();
		$arrCodes	= $this->getInputCodes();
        $arrBind    = $this->getAllCodesWithBind();
        $items    =Yii::app()
            ->db
            ->createCommand('SELECT * FROM item WHERE code IN ('.implode(',', array_keys($arrBind)).')')
            ->bindValues($arrBind)
            ->queryAll();

        foreach($arrCodes as $code)
        {
            foreach($items as &$item)
            {
                if( $item['code'] == $code )
                {
                    $item['qty'] = isset($item['qty'])?($item['qty']+1):1;
                    break;
                }
            }
        }
        return $this->items = $items;
    }

    public function getAllItemsAndCoupons()
    {
    	$items = $this->getAllItems();
    	$coupons = $this->getAllCoupons();
    	$data = $items;
        foreach($coupons as $coupon)
        {
            $data[] = $coupon;
        }
        return $data;		
    }

    public function generateOrder()
    {
        #Should open a transaction here
        $order = new Order();
        #$order->id_customer = NULL;
        $order->user_id             = 2;#Saler
        $order->date                = date('Y-m-d H:i:s');
        $order->created_time        = time();
        $order->last_updated_time   = time();
        if( $order->save() )
        {
            $items = $this->getAllItems();
            foreach($items as $item)
            {
				//This is not good for performance
				//because we create the instance of OrderDetail in loop
                $orderDetail = new OrderDetail();
                $orderDetail->setAttributes(array(
                    'order_id'      => (int)$order->getPrimaryKey(),
                    'item_id'       => (int)$item['item_id'],
                    'quantity'      => (int)$item['qty'],
                    'price'         => (int)$item['price'],
                    'created_time'  => time(),
                ));
                $orderDetail->save();
            }
        }
    }

    public function getAllCoupons()
    {
    	if( $this->coupons !== NULL )
    	{
    		return $this->coupons;
    	}
    	$arrBind    = $this->getAllCodesWithBind();
    	$coupons    =Yii::app()
            ->db
            ->createCommand('SELECT * 
                            FROM coupon
                            WHERE code IN ('.implode(',', array_keys($arrBind)).')
                            AND (:current_time BETWEEN from_date AND to_date) AND (order_id IS NULL)')
            ->bindValues($arrBind)
            ->bindValue(':current_time', time())
            ->queryAll();

        if( $coupons )
        {
            $this->hydratCoupon($coupons);
        }
        return $this->coupons = $coupons;
    }

    public function hydratCoupon(&$coupons)
    {
        foreach($coupons as &$coupon)
        {
            $coupon['item_id']      = '1';
            $coupon['size']         = '--';
            $coupon['title']        = 'Phiếu giảm giá';
            $coupon['qty']          = 1;
            $coupon['price']        = -$coupon['value'];
        }
    }

    public function getSubTotal()
	{
		$items = $this->getAllItems();
		$coupons = $this->getAllCoupons();
        $total = 0;
        foreach( $items as $item )
        {
            $total += $item['price']*$item['qty'];
        }
        foreach ($coupons as $coupon)
        {
            $total += $coupon['price'];
        }
        return $total;
    }
}